//与登录注册相关[用户]
import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo,reqLogout} from "@/api";
import { SET_TOKEN, GET_TOKEN,RESET_TOKEN} from "@/utils/USER_TOKEN";
const state = {
    //存储验证码
    code: '',
    token: GET_TOKEN(),
    userInfo:{}
};
const mutations = {
    GETCODE: (state, code) => {
        state.code = code
    },
    LOGIN: (state, token) => {
        state.token = token
    },
    SET_USERINFO:(state,userInfo) =>{
        state.userInfo = userInfo
    },
    RESET_USERINFO: (state) => {
        //清除token以及用户信息
        state.token = ""
        state.userInfo = {};
        //清除本地存储token
        RESET_TOKEN();

    }
};
const actions = {
    //获取验证码
    getCode: async ({ commit, state, dispatch }, phone) => {
        let result = await reqGetCode(phone);
        if (result.code == 200) {
            commit('GETCODE', result.data);
            return 'ok';
        } else {
            return Promise.reject()
        }
    },
    //注册用户
    userRegister: async ({ commit, state, dispatch }, user) => {
        //注册用户请求
        let result = await reqUserRegister(user);
        //返回成功与失败状态
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject();
        }
    },
    //登录
    login: async ({ commit, state, dispatch }, data) => {
        let result = await reqUserLogin(data);
        //登录返回的结果中有很重要 的一个东西 toden [后台给的]
        if (result.code == 200) {
            commit("LOGIN", result.data.token);
            //本地存储：持久化存储token
            SET_TOKEN(result.data.token);
            return 'ok'
        } else {
            return Promise.reject(result.message);
        }
    },
    //获取用户信息
    getUserInfo: async ({ commit, state, dispatch }) => {
        //发送请求获取用户信息
        let result = await reqUserInfo()
        if (result.code == 200) {
            commit('SET_USERINFO',result.data)
            console.log(result)
        }
    },
    //退出登录
    logout:async({commit,state,dispatch})=>{
        let result = await reqLogout()
        if (result.code == 200) {
            commit('RESET_USERINFO');
            return 'ok'
        }else{
            return Promise.reject()
        }
    }
};
const getters = {};

//默认暴露 小仓库对外暴露的是对象
export default {
    state,
    mutations,
    actions,
    getters
}